package ro.isdc.training.jpa.professor.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import ro.isdc.training.jpa.professor.dao.ProfessorDAO;
import ro.isdc.training.jpa.professor.domain.Professor;
import ro.isdc.training.jpa.professor.domain.ProfessorId;

/**
 * Professor Data Access Object Implementation
 * 
 * @author Andrei Chirila
 */
public class ProfessorDAOImpl implements ProfessorDAO {
	
	/**
	 * EntityManager reference. Will be injected by Spring
	 */
	@PersistenceContext
	private EntityManager entityManager;
	
	/**
	 * {@inheritDoc}
	 */
	public Serializable saveProfessor(final Professor professor) {
		entityManager.persist(professor);
		return professor.getEntityId();
	}

	/**
	 * {@inheritDoc}
	 */
	public Professor findProfessorByProfessorId(final ProfessorId professorId) {
		List<Object> paramValuesList = new ArrayList<Object>();
    List<String> paramNamesList = new ArrayList<String>();
    
		String sql = "select p from Professor p";
		
		if (professorId != null) {
    	if (professorId.getEntityId() > 0) {
    		sql += " where p.entityId = :entityId";
    		paramNamesList.add("entityId");
    		paramValuesList.add(professorId.getEntityId());
    	} else {
    		sql += " where p.SSN = :SSN";
    		paramNamesList.add("SSN");
    		paramValuesList.add(professorId.getSSN());
    	}
    }
		
		return (Professor) entityManager.createQuery(sql).setParameter(paramNamesList.get(0), 
				paramValuesList.get(0)).getSingleResult();
	}

}
